import asyncio
from evdev import InputDevice, categorize, ecodes

# 配置：替换为你的键盘设备路径
KEYBOARD_PATH = "/dev/input/event0"  # 通常event0是系统键盘

async def monitor_keys():
  device = InputDevice(KEYBOARD_PATH)
  key_states = {}  # 存储按键状态 {key_code: bool}

  async for event in device.async_read_loop():
      if event.type == ecodes.EV_KEY:
          key_event = categorize(event)
          key_code = key_event.scancode

          # 更新状态：KEYDOWN 时为 True，KEYUP 时为 False
          key_states[key_code] = (key_event.keystate == key_event.key_down)

          # 示例：实时打印当前事件（生产环境可删除）
          state = "DOWN" if key_states[key_code] else "UP  "
          print(f"Key {key_code:3} {state}")

  # 外部查询函数
  def is_key_pressed(key_scancode):
      return key_states.get(key_scancode, False)

  return is_key_pressed

# 启动监控（非阻塞）
loop = asyncio.get_event_loop()
query_func = loop.run_until_complete(monitor_keys())

# 示例用法：在主循环中查询状态
try:
  while True:
      # 示例：查询空格键（Scancode 57）
      if query_func(57):
          print("[空格键被按住]")

      # 非阻塞等待（避免CPU满载）
      loop.run_until_complete(asyncio.sleep(0.1))

except KeyboardInterrupt:
  print("\n程序退出")